<template>
  <i-form
      ref="formRef"
      :model="formData"
      :rules="state.formRules"
      :label-width="100"
      label-position="right"
      :inline="true"
      class="admin-form">
    <FormItem label="账号" prop="username">
      <Input v-model="formData.username" placeholder="请输入账号" :disabled="currentAccountType"/>
    </FormItem>
    <FormItem label="名称" prop="nickname">
      <Input v-model="formData.nickname" placeholder="请输入名称"/>
    </FormItem>
    <FormItem label="密码" prop="password" style="height: 50px">
      <Input v-model="formData.password" password type="password" placeholder="请输入密码"/>
    </FormItem>
    <FormItem label="确认密码" prop="confirmPassword" style="height: 50px">
      <Input v-model="formData.confirmPassword" password type="password" placeholder="请输入确认密码"/>
    </FormItem>
    <FormItem label="管理员角色" prop="role_id">
      <Select v-model="formData.role_id" :disabled="currentAccountType">
        <Option v-for="item in props.roleData" :value="item.id" :key="item.id">{{ item.name }}</Option>
      </Select>
    </FormItem>
    <FormItem label="管理员状态" prop="status" v-if="mode === 'add'">
      <i-switch v-model="formData.status" :true-value="1" :false-value="0"></i-switch>
    </FormItem>
  </i-form>
</template>

<script setup>

import {getCurrentInstance, reactive, ref} from "vue";
import {AdminService} from "@/api/admin";
import {Select, Option} from "view-ui-plus";
import {deepCloneObj} from "@/api/utils";

const mode = ref('');

const {proxy} = getCurrentInstance();

const props = defineProps({
  roleData: {
    type: Array,
    default: () => {
      return []
    }
  }
})

const formData = reactive({
  id: '',
  username: '',
  nickname: '',
  role_id: '',
  password: '',
  confirmPassword: '',
  status: 1
})

const currentAccountType = ref(0);

/**
 * 自定义密码校验规则1
 * @param rule
 * @param value
 * @param callback
 */
const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('密码不能为空!'));
  } else if (!(/^[a-zA-Z0-9_-]{4,16}$/.test(value))) {
    callback(new Error('密码只能是6至10位且包含字母、数字、下划线和破折号!'))
  } else {
    if (formData.confirmPassword !== '') {
      proxy.$refs.formRef.validateField('confirmPassword');
    }
    callback();
  }
}

/**
 * 自定义密码校验规则2
 * @param rule
 * @param value
 * @param callback
 */
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码!'));
  } else if (!(/^[a-zA-Z0-9_-]{4,16}$/.test(value))) {
    callback(new Error('密码只能是6至10位且包含字母、数字、下划线和破折号!'))
  } else if (value !== formData.password) {
    callback(new Error('两次密码不一致!'))
  } else {
    callback();
  }
}


const state = reactive({
  formRules: {
    username: [{required: true, message: '账号不能为空!'}, {
      type: 'string',
      pattern: /^[a-zA-Z0-9-]{6,10}$/,
      message: '用户名只能为6至10位且字母、数字!'
    }],
    nickname: [{required: true, message: '名称不能为空!'}],
    role_id: [{required: true, message: '角色不能为空!'}],
    password: [{validator: validatePassword}],
    confirmPassword: [{validator: validateConfirmPassword}],
    status: [{required: true, message: '管理员状态不能为空!'}]
  }
})

const addAdminData = () => {
  console.log(mode)
  proxy.$refs.formRef.validate(valid => {
    console.log(valid)
    if (!valid) {
      Promise.reject()
      return false;
    } else {
      console.log(mode.value)
      if (mode.value === 'add') {
        post();
      } else {
        console.log('编辑')
        edit();
      }
    }
  })
}

const post = async () => {
  // 深克隆对象并删除确认密码
  const param = deepCloneObj(formData);
  delete param.confirmPassword;
  // param.password = Md5(param.password);
  // console.log(formData)
  const {data} = await AdminService.AddAdmin(param);
  if (data.code === 200) {
    proxy.$Message.success({
      content: data.data,
      duration: 1.5,
      onClose: () => {
        // CommonServices.getMenus();
        window.location.reload()
      }
    })
  } else {
    proxy.$Message.error({
      content: data.data,
      duration: 1.5,
      onClose: () => {
        Promise.reject()
      }
    })
  }
}

const getDetail = async (e) => {
  const param = {
    id: e.id
  };
  const {data} = await AdminService.GetAdminById(param);
  if (data.code === 200) {
    console.log(data.data)
    setFormData(data.data);
  } else {
    proxy.$Message.error({
      content: data.data,
      duration: 1.5,
      onClose: () => {
        Promise.reject();
      }
    })
  }
}

const setFormData = (data) => {
  currentAccountType.value = data.root
  Object.assign(formData, data)
}

const edit = async () => {
  // 深克隆对象并删除确认密码
  const param = deepCloneObj(formData);
  delete param.confirmPassword;
  // param.password = Md5(param.password);
  const {data} = await AdminService.ModifyAdminInfo(param);
  if (data.code === 200) {
    proxy.$Message.success({
      content: data.data,
      duration: 1.5,
      onClose: () => {
        window.location.reload();
      }
    })
  } else {
    proxy.$Message.error({
      content: data.data,
      duration: 1.5,
      onClose: () => {
        Promise.reject();
        return false;
      }
    })
  }
}

defineExpose({
  addAdminData,
  mode,
  getDetail
})

</script>

<style scoped lang="less">
@import "admin-edit.less";
</style>
